// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from "vue"
import App from "./App"
import router from "./router"
import store from "./store"
import "element-ui/lib/theme-chalk/index.css"
import "@/css/base.css"
import "@/css/element.css"
import "@/font/iconfont.css"
import "@/js/directives.js"

//elementUi
import ElementUI from "element-ui"
Vue.use(ElementUI, {size: 'small'})

//echarts数据统计
import echarts from "echarts"
Vue.prototype.$echarts = echarts

//axios请求
import axios from "axios"
//axios 请求超时  axios挂载在vue上  axios没有use
axios.defaults.headers.post['Content-Type'] = 'application/json';
//axios.defaults.baseURL = 'http://192.168.2.16:8080';
axios.defaults.timeout = 30000;
Vue.prototype.$http = axios;
//参数拼
import qs from "qs"
Vue.prototype.qs = qs;

//关闭vue启动时生成生产
Vue.config.productionTip = false

const CancelToken = axios.CancelToken;
let cancel = null     //中断请求

// http request 拦截器 放在vue 对象前面 防止第一次加载不执行
axios.interceptors.request.use(
    config => {
        if (!config.headers.isCancel) {      //请求头headers 有isCancel:false  不参与中断
            if (cancel) cancel()    //中断请求
            config.cancelToken = new CancelToken(c => {
                cancel = c
            })
        }
        //为请求添加session  如果没有等后台返回401状态跳转登陆
        let token = sessionStorage.getItem('token')
        let expire = sessionStorage.getItem('expire')
        if (token && expire) {
            config.headers.token = token;
            config.headers.expire = expire;
        }
        return config;
    }
);

// http response 拦截器  放在vue 对象前面 防止第一次加载不执行
axios.interceptors.response.use(
    res => {
        //有返回数据就清空上当前请求记录
        if(!res.data.success &&res.data.errorCode && res.data.errorCode =='SC_UNAUTHORIZED'){
            Vm.$alert('登陆已过期,请重新登陆！！！', '登陆提示', {
                confirmButtonText: '确定',
                closeOnPressEscape:true,
                callback: action => {
                    sessionStorage.removeItem('token');
                    sessionStorage.removeItem('expire')
                    sessionStorage.removeItem('usermsg')
                    window.location.href = '/login?redirect='+ Vm.$route.path    //浸入式跳转，防止页面缓存
                }
            })

        }else{
            return res;
        }

    },
    //判断 中断请求/请求超时/其他错误
    error => {
        let _error = error.config;
        if(error == 'Cancel'){
            console.log('【中断忽略的请求】'+error);
            //被中断请求 _eroor 返回的是Cancel 对象
            return Promise.reject({'Cancel':error})

        }else if(error.code == 'ECONNABORTED' && error.message.indexOf('timeout')!=-1 && !_error._retry){
            Vm.$message({
                showClose: true,
                message: '请求超时！',
                type: 'error'
            });
            console.log('【请求超时】'+error.message)
            return Promise.reject({'timeout':error.message})

        }else{
            Vm.$message({
                showClose: true,
                message: '服务器未响应！',
                type: 'error'
            });
            console.log('【请求错误】'+error.message)
            return Promise.reject({'state':{'errorMsg':error.response.data,'state':error.response.status}})

        }
    }
);

//路由拦截登陆    写在new Vue前 可以防止直接输入url地址不跳转登陆
router.beforeEach((to, from, next) => {
    if(cancel){
        cancel()
    }
    if (to.path === '/login') {
        next()
    } else {
        if (!sessionStorage.getItem('token')) {
            next({path: '/login', query: {redirect: to.fullPath}})
        } else {
            next()
        }
    }
})
let Vm = new Vue({
    el: '#app',
    store,//使用store
    router,
    render: h => h(App)
})